﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ReferenceTemplate.ViewModels;
using System.Windows.Data;
using Microsoft.Phone.Net.NetworkInformation;

namespace ReferenceTemplate.WindowsPhone.Views
{
    public partial class DetailPage : PhoneApplicationPage
    {
        public DetailPage()
        {
            InitializeComponent();
        }

        private void PinToStart_Click(object sender, EventArgs e)
        {
            MainViewModel viewModel = DataContext as MainViewModel;

            if(viewModel != null)
            {
                viewModel.PinToStart.Execute(viewModel.SelectedLink);
            }
        }

        private void CopyLink_Click(object sender, EventArgs e)
        {
            MainViewModel viewModel = DataContext as MainViewModel;

            if (viewModel != null)
            {
                viewModel.CopyLink.Execute(viewModel.SelectedLink);
            }
        }

        private void OpenLink_Click(object sender, EventArgs e)
        {
            MainViewModel viewModel = DataContext as MainViewModel;

            if (viewModel != null)
            {
                viewModel.OpenLink.Execute(viewModel.SelectedLink);
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            Loaded += (r, arg) =>
            {
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    MessageBox.Show("La aplicación necesita internet para mostrar el contenido", "No hay internet!", MessageBoxButton.OK);
                }

                MainViewModel viewModel = DataContext as MainViewModel;

                if(viewModel != null)
                {
                    string[] parameters = e.Uri.OriginalString.Split('=');

                    if (parameters.Count() >= 2)
                    {
                    

                        viewModel.SelectedLink = viewModel.Links.Where(link => link.Id.Equals(parameters[1])).FirstOrDefault();
                    }
                }
                
            };
            
            
            
        }
        
    }
}